// Copyright (c) 2020 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

/**
*@describe:
*@author wfl19/Kristas
*@date 2021/12/17
 */

package datasource

import (
	"fmt"
	"gitee.com/kristas/booting-go/framework"
	"gitee.com/kristas/booting-go/framework/core/statement/types"
)

func init() {
	framework.Component(new(DBAwarePostProcessorBean))
}

type DBAwarePostProcessorBean struct {
	types.Component `name:"db_aware_post_processor_bean"`
	DataSources     []DataSource `wire:""`
}

func (p *DBAwarePostProcessorBean) PostProcessorBeforeInitialization(bean interface{}, beanName string) error {
	awareBean, ok := bean.(BeanDBAware)
	if !ok {
		return nil
	}
	var awared bool
	for _, ds := range p.DataSources {
		if ds.Bean() == awareBean.DataSource() {
			awareBean.SetDB(ds.DB())
			awared = true
		}
	}
	if !awared {
		return fmt.Errorf("aware db for: %s, failed: could not found datasource: %s", beanName, awareBean.DataSource())
	}
	return nil
}

func (p *DBAwarePostProcessorBean) PostProcessorAfterInitialization(bean interface{}, beanName string) error {
	return nil
}
